package api;

import model.User;
import model.UserDao;
import view.HtmlGenerator;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
// 浏览器通过POST 方法提交注册信息给服务器
public class RegisterServlet extends HttpServlet {
    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        // 1. 获取从前端得到的数据并进行合法校验
        req.setCharacterEncoding("utf-8");
        resp.setContentType("text/html; charset=utf-8");
        String name = req.getParameter("name");
        String password = req.getParameter("password");
        if(name == null || "".equals(name) || password == null || password.equals("")){
            // 用户提交的数据有误
            // 返回一个错误页面;
            String html = HtmlGenerator.getMessagePage("用户名或密码为空","register.html");
            resp.getWriter().write(html);
            return;
        }
        // 2. 拿着用户名五数据库中查一下,如果数据库中有,那也要返回一个错误页面;
        UserDao userDao = new UserDao();
        User existUser = userDao.selectByName(name);
        if(existUser != null){
            String html = HtmlGenerator.getMessagePage("用户名重复,请换一个!","register.html");
            resp.getWriter().write(html);
            return ;
        }

        // 3. 所有校验 可以构造对象
        User user = new User();
        user.setName(name);
        user.setPassword(password);
        userDao.add(user);
        // 返回一个结果页面
        String html = HtmlGenerator.getMessagePage("注册成功! 点击跳转到登录页面!","login.html");
        resp.getWriter().write(html);
        return;
    }
}
